<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2017-07-10
 * Time: 15:34
 */

namespace app\index\helper;

use app\src\base\helper\ResultHelper;
use app\src\base\helper\ValidateHelper;
use app\src\base\logic\BaseLogic;
use app\src\email\action\EmailSendAction;
use app\src\extend\umeng\BoyePushApi;
use app\src\sunsun\common\logic\DeviceTcpClientLogic;
use app\src\sunsun\common\logic\PushLogLogic;
use app\src\sunsun\common\logic\UserDeviceLogic;
use app\src\system\logic\ConfigLogic;
use app\src\user\logic\UcenterMemberLogic;
use think\Lang;

class CommandHelper
{
    // pondlink的邮箱配置
    public static $pondLinkEmail = [
        "smtp_username" => "my.filter@pondlink.com",
        "smtp_port" => "25",
        "smtp_send_email" => "my.filter@pondlink.com",
        "smtp_sender_name" => "pondlink.com",
        "smtp_password" => "!Oi+2018-",
        "smtp_host" => "send.one.com"
    ];

    public static function loadLang($langs=[]){
        $path = APP_PATH.'index/lang/';
        foreach ($langs as $lang){
            Lang::load($path.$lang.'.php',$lang);
        }
    }

    public static function offline_notify($size,BaseLogic $deviceLogic,$deviceType){
        // 每次 1千
        $page = ['curpage'=>0,'size'=>$size];
        $now = time() - 10 * 60; //离线 10 分钟以上的设备
        // 状态为 1 且 离线 2 分钟以上的设备 且
        $map  = ['tcp_client_id'=>'','offline_notify'=>1,'update_time'=>['lt',$now]];
        $result = $deviceLogic->query($map,$page,'update_time asc',"","id,did,ctrl_pwd,last_login_time");
        // echo ''.lang('device_notify_title');
        $list = $result['info']['list'];
        $result = self::offline($deviceLogic,$list,$deviceType);

        // 处理 tcp_client_id 不等空字符串的情况
        $now = time() - 720; // 半小时没有心跳更新，则断开
        $map  = ['update_time'=>['lt',$now]];
        $map['tcp_client_id'] = ['neq',''];
        $deviceLogic->save($map,['tcp_client_id'=>'']);

        $now = time() - 24*3600; // 1天以前登录的
        $map  = ['prev_login_time'=>['lt',$now]];
        $map['tcp_client_id'] = ['neq',''];
        (new DeviceTcpClientLogic())->save($map,['tcp_client_id'=>'']);

        return $result;
    }

    public static function offline(BaseLogic $deviceLogic, $list, $deviceType)
    {
        $userDeviceLogic = new UserDeviceLogic();
        $entity = [];
        $ucenterMemberLogic = new UcenterMemberLogic();
        try{
            $tcpClientLogic = new DeviceTcpClientLogic();
            $now = time();
            foreach ($list as $item){
                $did = $item['did'];
                $ctrl_pwd = $item['ctrl_pwd'];
                array_push($entity, ['id'=>$item['id'],'offline_notify'=>2]);

                // 如果设备离线则重置上次推送的信息时间
                (new PushLogLogic())->save(['did'=>$did],['last_push_time'=>0]);
                // 只获取最新的20个用户信息
                $result = $userDeviceLogic->query(['did'=>$did],['curpage'=>1,'size'=>20],'update_time desc');

                if(!ValidateHelper::legalArrayResult($result) || empty($result['info']['list'])) {
                    continue;
                }

                $userDeviceList = $result['info']['list'];

                foreach ($userDeviceList as $deviceItem) {
                    $uid = $deviceItem['uid'];
                    $nickname = $deviceItem['device_nickname'];
                    $lang = $deviceItem['lang'];
                    $extra = json_decode($deviceItem['extra'],JSON_OBJECT_AS_ARRAY);
                    $notify_email = array_key_exists('notify_email', $extra) ? intval($extra['notify_email']) : 0;

                    if (!is_array($extra) || !array_key_exists("pwd", $extra) || ($extra['pwd'] != 'sunsun123456' && $extra['pwd'] != $ctrl_pwd)) {
                        // 密码不一致或没有密码就不需要处理
                        continue;
                    }
                    $result = $ucenterMemberLogic->getInfo(['id' => $uid]);
                    $member = $result['info'];
                    // 向绑定该设备的用户手机推送
                    $data = [
                        'to_uid' => $uid,
                        'title' => lang('device_notify_title', ['nickname' => $nickname, 'device_type' => lang($deviceType, '', $lang)], $lang),
                        'content' => lang('device_offline_notify_content', ['nickname' => $nickname], $lang)
                    ];
                    if ($notify_email == 1) {// 等于1 才进行邮件推送
                        $email = $member['email'];
                        $result = (new EmailSendAction())->send($email, $data['title'], $data['content'], self::$pondLinkEmail);
                    } else {
                        // 向绑定该设备的用户手机推送
                        CommandHelper::pushUMeng($data);
                    }
                }
            }
        }catch (\Exception $ex){

        }finally{
            $result = $deviceLogic->saveAll($entity);
            return $result;
        }
    }

    public static function getCtrlPwd($did,$logic){
        if(method_exists($logic,"getInfo")){
            $result = $logic->getInfo(['did'=>$did]);
            if(ValidateHelper::legalArrayResult($result) && $result['info']['did'] == $did){
                return $result['info']['ctrl_pwd'];
            }
        }
        return '';
    }

    public static function getDeviceInfo($did,$logic){
        if(method_exists($logic,"getInfo")){
            $result = $logic->getInfo(['did'=>$did]);
            if(ValidateHelper::legalArrayResult($result) && $result['info']['did'] == $did){
                return $result['info'];
            }
        }
        return null;
    }

    public static function pushUMeng($data){
        $to_uid = $data['to_uid'];
        $content = $data['content'];
        $title   =  $data['title'];
        $msg_type = "00Q002001";

        $pushApi = new BoyePushApi();
        $after_open  = [
            'type'  => 'go_activity',
            'param' => $msg_type,
            'extra' => [],//'uid'=>$to_uid]
        ];
        $body = [
            // 'alert'  =>$summary,
            'alert'  =>$content,
            'ticker' =>$title,
            'title'  =>$title,
            'text'   =>$content
        ];

        $list = cache('g_push_config');
        if(empty($list)){
            $result = (new ConfigLogic())->queryNoPaging(['group'=>11]);
            // 增加缓存
            if(ValidateHelper::legalArrayResult($result)) {
                $list = $result['info'];
                // 缓存3天
                cache('g_push_config',$list,72*3600);
            }
        }
        if(!empty($list)){
            foreach ($list  as $vo){
                $value = $vo['value'];
                $value = self::_parse($vo['type'],$value);

                if(is_array($value)){
                    if (!$pushApi->setConfig($value)) {
                        continue;
                    }
                }

                $result = $pushApi->send($to_uid,$body,$after_open);
                if(!$result['status']) {
                }

            }

        }
        return ResultHelper::success('success');
    }

    private static function _parse($type, $value) {
        switch ($type) {
            case 3 :
                $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
                if (strpos($value, ':')) {
                    $value = array();
                    foreach ($array as $val) {
                        list($k, $v) = explode(':', $val,2);
                        $value[$k] = $v;
                    }
                } else {
                    $value = $array;
                }
                break;
        }
        return $value;
    }
}